package com.itbird.eventbus.core;

/**
 * 享元设计模式，缓存复用
 * Created by itbird on 2022/9/20
 */
public class PendingPost {
    public static final Object sPoolSync = new Object();
    PendingPost next;
    private static PendingPost sPool;
    private static int sPoolSize = 0;
    private static final int MAX_POOL_SIZE = 50;

    private SubscribeMethod subscription;
    private Object event;

    public SubscribeMethod getSubscription() {
        return subscription;
    }

    public Object getEvent() {
        return event;
    }

    private PendingPost() {
    }

    public static PendingPost obtainPendingPost(SubscribeMethod subscription, Object event) {
        PendingPost m = obtainPendingPost();
        m.subscription = subscription;
        m.event = event;
        return m;
    }

    public static PendingPost obtainPendingPost() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                PendingPost m = sPool;
                sPool = m.next;
                m.next = null;
                sPoolSize--;
                return m;
            }
        }
        return new PendingPost();
    }

    public void recycle() {
        subscription = null;
        event = null;
        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }
}
